#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAX_CMD 1000
int parseline(char *buf,char**argv){
    while(*buf==' '){
        buf++;
    }
    int delim = 0;
    
    int argc = 0;
    while(*buf!='\n'){
        
        while(buf[delim]!='\n'&&buf[delim]!=' '){
            delim++;
        }
        
        if(buf[delim] == '\n'){
            buf[delim] = '\0';
            argv[argc++] = buf;
            break;
        }
        buf[delim] = '\0';
        argv[argc++] = buf;
        buf+=delim+1;
        delim = 0;
        while(*buf==' '){
            buf++;
        }
    }
    argv[argc] = NULL;
    return 0;
}

void eval(char *cmdstring){
    char *argv[MAX_CMD];
    char buf[MAX_CMD];
    strcpy(buf,cmdstring);
    parseline(buf,argv);
    if(strcasecmp(argv[0], "exit") == 0)
        {
            exit(0);//不管exit后面是否还有参数，直接退出
        }
 
    if(argv[0]==NULL){
        return;/*ignore empty lines*/
    }
    int pid = fork();
   if(pid == 0){
        if(execvp(argv[0],argv)<0){
            printf("%s:command not found.\n",argv[0]);
            exit(0);
        }
    }
    wait(&pid);
}


int main(int argc,char *argv[]){
    
    char cmdstring[MAX_CMD];
    int n;
    while(1){
        printf("myshell $ >");
        fflush(stdout);
        if((n=read(0,cmdstring,MAX_CMD))<0){
            printf("read error");
        }
        eval(cmdstring);
    }
    return 0;
}
